package com.my.ads.lib.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.myadlib.R;
import com.my.ads.lib.AdSummary;
import com.my.ads.lib.Config;
import com.my.ads.lib.bean.WeatherBean;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuanyang on 2018/3/6.
 */

public class WeatherActivity extends BaseActivity {
    private HttpClient mHttpClient = null;
    private Handler handler = new Handler();
    private InputStream mInputStream = null;

    private List<WeatherBean> longTermWeather = new ArrayList<>();
//    private List<WeatherBean> longTermTodayWeather = new ArrayList<>();
//    private List<WeatherBean> longTermTomorrowWeather = new ArrayList<>();

    private String lat = "35";
    private String lon = "139";

    private String appId = "614d8aa41fd3a436a19a6ee6adc5b6f9";

    private TextView weatherTemperature, weatherDescription, weatherWind, weatherPressure, weatherHumidity, weatherDate;
    private ImageView imgOff, imgAd;
    private RelativeLayout relative_ad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        initViews();
        mShare();
    }


    public void mShare() {

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
        String result = sp.getString("lastLongTerm", "");
        long now = System.currentTimeMillis() / 1000;
        long endTime = sp.getLong("lastTime", 0L);
        if (!TextUtils.isEmpty(result) && now < endTime) {
            try {
                JSONObject reader = new JSONObject(result);
                longTermWeather = new ArrayList<>();

                JSONArray list = reader.getJSONArray("list");
                for (int i = 0; i < list.length(); i++) {
                    JSONObject listItem = list.getJSONObject(i);

                    long dt = Long.valueOf(listItem.getString("dt"));
                    if (now < dt) {
                        WeatherBean weather = makeWeatherBean(listItem);
                        updateLongTermWeatherUI(weather);
                        return;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    mHttpClient = new DefaultHttpClient();
                    HttpParams params = mHttpClient.getParams();
                    // 更换一个KEY
                    String loginUrl = "http://api.openweathermap.org/data/2.5/forecast?lat=" + lat + "&lon=" + lon + "&appId=" + appId;

                    HttpPost post = new HttpPost(loginUrl);
                    HttpResponse response = mHttpClient.execute(post);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        mInputStream = response.getEntity().getContent();
                        String str = "";
                        String state = "";
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(mInputStream));
                        String readLine = null;
                        while ((readLine = br.readLine()) != null) {
                            // response = br.readLine();
                            str = str + readLine;
                        }
                        parseLongTermJson(str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mHttpClient.getConnectionManager().shutdown();
                    if (mInputStream != null) {
                        try {
                            mInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }.start();
    }

    /**
     * ret 1 : CITY_NOT_FOUND
     * 2 : JSON_EXCEPTION
     * 3 : OK
     */

    public int parseLongTermJson(String result) {
        int i;
        try {
            JSONObject reader = new JSONObject(result);

            final String code = reader.optString("cod");
            if ("404".equals(code)) {
                if (longTermWeather == null) {
                    longTermWeather = new ArrayList<>();
                }
                return 1;
            }

            longTermWeather = new ArrayList<>();

            JSONArray list = reader.getJSONArray("list");
            for (i = 0; i < list.length(); i++) {
                WeatherBean weather = new WeatherBean();
                JSONObject listItem = list.getJSONObject(i);
                weather = makeWeatherBean(listItem);
                longTermWeather.add(weather);

            }
            if (longTermWeather.size() <= 0) {
                return 1;
            }
            new Thread() {
                @Override
                public void run() {//在run()方法实现业务逻辑；
                    //更新UI操作；
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateLongTermWeatherUI(longTermWeather.get(0));
//                            myTest();
                        }
                    });

                }
            }.start();

            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
            editor.putString("lastLongTerm", result);
            editor.putLong("lastTime", longTermWeather.get(longTermWeather.size() - 1).getDate().getTime());
//            Log.i(Constants.LogTag, String.valueOf(System.currentTimeMillis()));
//            Log.i(Constants.LogTag, String.valueOf(longTermWeather.get(longTermWeather.size() - 1).getDate().getTime()));
            editor.commit();
        } catch (JSONException e) {
            e.printStackTrace();
            return 2;
        }

        return 1;
    }


    public static String getRainString(JSONObject rainObj) {
        String rain = "0";
        if (rainObj != null) {
            rain = rainObj.optString("3h", "fail");
            if ("fail".equals(rain)) {
                rain = rainObj.optString("1h", "0");
            }
        }
        return rain;
    }


//    private void myTest() {
//        if (longTermTodayWeather != null && longTermTodayWeather.size() > 0) {
//            for (WeatherBean tmp : longTermTodayWeather) {
//                Log.i(Constants.LogTag, String.valueOf(tmp.getDate().getTime()));
//            }
//        }
//    }


    public void updateLongTermWeatherUI(WeatherBean weatherBean) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH");
        String time = format.format(weatherBean.getDate().getTime());
        weatherDate.setText("Date: " + time);
        weatherDescription.setText(weatherBean.getDescription());
        weatherHumidity.setText("Humidity: " + weatherBean.getHumidity() + " %");
        weatherPressure.setText("Pressure: " + weatherBean.getPressure() + " hpa");
        DecimalFormat df = new DecimalFormat("#.00");
        weatherTemperature.setText(df.format(Double.valueOf(weatherBean.getTemperature()) * 1.8 - 459.67) + " °F");
        weatherWind.setText("Wind: " + weatherBean.getWind() + " m/s");
    }

    private void initViews() {
        weatherDate = (TextView) findViewById(R.id.weatherDate);
        weatherDescription = (TextView) findViewById(R.id.weatherDescription);
        weatherHumidity = (TextView) findViewById(R.id.weatherHumidity);
        weatherPressure = (TextView) findViewById(R.id.weatherPressure);
        weatherTemperature = (TextView) findViewById(R.id.weatherTemperature);
        weatherWind = (TextView) findViewById(R.id.weatherWind);

        imgAd = (ImageView) findViewById(R.id.img_ad);
        imgOff = (ImageView) findViewById(R.id.img_off);

        relative_ad = (RelativeLayout) findViewById(R.id.relative_ad_18);

        imgOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AdSummary.getInstance().showInterstitialAd(WeatherActivity.this, "");
                finish();
            }
        });

        imgAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intents = new Intent(WeatherActivity.this, GiftActivity.class);
                startActivity(intents);
                AdSummary.getInstance().showInterstitialAd(WeatherActivity.this, "");
            }
        });

        AdSummary.getInstance().showNativeAd(this, relative_ad, false);
    }

    private WeatherBean makeWeatherBean(JSONObject listItem) {
        WeatherBean weather = null;
        try {
            weather = new WeatherBean();
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));

            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            if (windObj != null) {
                weather.setWind(windObj.getString("speed"));
//                weather.setWindDirectionDegree(windObj.getDouble("deg"));
            }
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";

            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);
        } catch (Exception e) {
            e.printStackTrace();
            weather = null;
        }

        return weather;
    }

    @Override
    protected void onResume() { // 按照Activity 来应该作修改
        super.onResume();
        SharedPreferences sp_1 = getSharedPreferences(Config.NativeAdTarget, Context.MODE_PRIVATE);
        Long show_time = sp_1.getLong(Config.NativeAdTimeShow, 0L);
        // 刷新原生广告
        if (show_time != 0L && ((System.currentTimeMillis() - show_time) > Config.UpdateNativeAd * 1000)) {
            try {
                AdSummary.getInstance().showNativeAd(this, relative_ad, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
